package com.ztsoft.user.service.dynamic.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ztsoft.user.mapper.dynamic.ColumnDescriptionMapper;
import com.ztsoft.user.pojo.constant.UserConstant;
import com.ztsoft.user.pojo.entity.dynamic.ColumnDescription;
import com.ztsoft.user.pojo.entity.dynamic.ColumnDescriptionUser;
import com.ztsoft.user.pojo.entity.user.SysDept;
import com.ztsoft.user.pojo.entity.user.SysUser;
import com.ztsoft.user.pojo.vo.dynamic.ColumnDescriptionVo;
import com.ztsoft.user.pojo.vo.dynamic.CustomColumnVo;
import com.ztsoft.user.service.dynamic.ColumnDescriptionService;
import com.ztsoft.user.service.dynamic.ColumnDescriptionUserService;
import com.ztsoft.user.service.user.SysDeptService;
import com.ztsoft.user.service.user.SysUserService;
import com.ztsoft.user.utils.JWTUtils;
import com.ztsoft.user.utils.UserHolder;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class ColumnDescriptionServiceImpl extends ServiceImpl<ColumnDescriptionMapper, ColumnDescription> implements ColumnDescriptionService {

    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private SysDeptService sysDeptService;
    @Autowired
    private ColumnDescriptionUserService columnDescriptionUserService;

    /**
     * 保存列
     */
    @Override
    public void saveColumnDescription(ColumnDescription columnDescription) {
        //获取前端给的id，判断部门，还是用户    dept_id
        String deptId = columnDescription.getDeptId();
        SysUser sysUser = sysUserService.getById(deptId);
        SysDept dept = sysDeptService.getById(deptId);

        //1、如果要添加用户数据
        if (sysUser != null) {
            ColumnDescriptionUser columnDescriptionUser = new ColumnDescriptionUser();
            BeanUtils.copyProperties(columnDescription, columnDescriptionUser);
            columnDescriptionUser.setUserId(sysUser.getUserId());
            List<ColumnDescription> descriptionList = columnDescriptionUserService.queryColumnByTableCode(columnDescriptionUser);

            //如果用户数据没有新增过
            if (descriptionList.isEmpty()) {
                ColumnDescription queryCol = new ColumnDescription();
                queryCol.setDeptId(sysUser.getDeptId().toString());
                queryCol.setTableCode(columnDescription.getTableCode());

                List<ColumnDescription> columnDescriptionList = baseMapper.selectList(new QueryWrapper<>(queryCol).orderBy(true, true, "sequence"));
                for (ColumnDescription description : columnDescriptionList) {
                    ColumnDescriptionUser descriptionUser = new ColumnDescriptionUser();
                    BeanUtils.copyProperties(description, descriptionUser);
                    descriptionUser.setUserId(sysUser.getUserId());
                    columnDescriptionUserService.saveColumnDescription(descriptionUser);
                }
            }
            //用户新增过
            columnDescriptionUserService.saveColumnDescription(columnDescriptionUser);
        } else if (dept != null) {  //2、如果添加模板数据
            //获取前端添加的列
            List<Map<String, String>> listMap = columnDescription.getCorrespondingField();

            Date date = new Date(System.currentTimeMillis());
            //获取列表最大序列值
            int maxSequence = baseMapper.getMaxSequence(columnDescription.getTableCode(), deptId);
            columnDescription.setCreateTime(date);
            columnDescription.setModifyTime(date);

            if (!listMap.isEmpty()) {
                //遍历添加的列，按每列添加
                for (Map<String, String> map : listMap) {
                    String selectField = map.get("COLUMN_NAME");
                    String title = map.get("COLUMN_COMMENT");
                    maxSequence++;
                    //设置给前端的key
                    ColumnDescription columnDescription1 = new ColumnDescription();
                    BeanUtils.copyProperties(columnDescription, columnDescription1);
                    columnDescription1.setField(selectField.replace('#', '_'));
                    columnDescription1.setTitle(title);
                    //将 表#列  变更为 表.列
                    selectField = selectField.replace('#', '.');
                    //设置sql里查询的字段
                    columnDescription1.setSelectField(selectField);
                    columnDescription1.setSequence(maxSequence);
                    baseMapper.insert(columnDescription1);
                }
            }
            baseMapper.insert(columnDescription);
        }
    }

    /**
     * 获取表格列
     */
    @Override
    public List<ColumnDescription> queryColumnByTableCode(ColumnDescription columnDescription) {
        //获取前端给的id，判断部门，还是用户
        String deptId = columnDescription.getDeptId();
        SysUser sysUser = sysUserService.getById(deptId);
        SysDept dept = sysDeptService.getById(deptId);

        List<ColumnDescription> list = new ArrayList<>();

        if (sysUser != null) {//查用户自定义列
            ColumnDescriptionUser columnDescriptionUser = new ColumnDescriptionUser();
            BeanUtils.copyProperties(columnDescription, columnDescriptionUser);
            columnDescriptionUser.setUserId(deptId);
            list = columnDescriptionUserService.queryColumnByTableCode(columnDescriptionUser);
            if (list.isEmpty()) {//如果用户数据为空，取用户对应部门的模板数据
                columnDescription.setDeptId(sysUser.getDeptId().toString());
                list = baseMapper.selectList(new QueryWrapper<>(columnDescription).orderBy(true, true, "sequence"));
            }
        } else if (dept != null) {  //查模板列
            list = baseMapper.selectList(new QueryWrapper<>(columnDescription).orderBy(true, true, "sequence"));
        }
        return list;
    }

    /**
     * 获取id和列名
     */
    @Override
    public List<ColumnDescription> queryIdAndTitle(ColumnDescription columnDescription) {
        QueryWrapper<ColumnDescription> wrapper = new QueryWrapper<>(columnDescription)
                .select("id", "title")
                .orderBy(true, true, "sequence");
        return baseMapper.selectList(wrapper);
    }

    /**
     * 修改列
     */
    @Override
    public void updateColumnDescription(ColumnDescription columnDescription) {
        //获取前端给的id，判断部门，还是用户
        String deptId = columnDescription.getDeptId();
        SysUser sysUser = sysUserService.getById(deptId);
        SysDept dept = sysDeptService.getById(deptId);

        if (dept != null) {
            baseMapper.updateById(columnDescription);
        } else if (sysUser != null) {
            ColumnDescriptionUser columnDescriptionUser = new ColumnDescriptionUser();
            BeanUtils.copyProperties(columnDescription, columnDescriptionUser);
            columnDescriptionUser.setUserId(deptId);
            columnDescriptionUserService.saveOrUpdate(columnDescriptionUser);
        }

    }

    //生成列
    @Override
    public List<ColumnDescriptionVo> getColumnDescriptionVos(String tableCode) {
        //获取用户自定义列表
        List<ColumnDescription> descriptionList = getColumnDescriptions(tableCode);

        List<ColumnDescriptionVo> list = new ArrayList<>();
        descriptionList.forEach(column -> {
            ColumnDescriptionVo columnDescriptionVo = new ColumnDescriptionVo();
            BeanUtils.copyProperties(column, columnDescriptionVo);
            if (Boolean.FALSE.equals(column.getExhibition())) {
                columnDescriptionVo.setVisible(false);
            }
            list.add(columnDescriptionVo);
        });
        return list;
    }

    /**
     * 显示自定义列
     */
    @Override
    public List<CustomColumnVo> queryCustomColumnList(String tableCode) {
        List<ColumnDescription> descriptionList = getColumnDescriptions(tableCode);
        List<CustomColumnVo> list = new ArrayList<>();
        descriptionList.stream().filter(columnDescription ->
                (columnDescription.getField() != null && !columnDescription.getField().isEmpty() && !"主键".equals(columnDescription.getTitle()))
        ).collect(Collectors.toList()).forEach(column -> {
            CustomColumnVo customColumnVo = new CustomColumnVo();
            BeanUtils.copyProperties(column, customColumnVo);
            customColumnVo.setDataIndex(column.getField());
            customColumnVo.setExhibition(column.getVisible());
            list.add(customColumnVo);
        });
        return list;
    }

    /**
     * 保存自定义列
     */
    @Override
    public void saveCustomColumn(List<CustomColumnVo> list, String tableCode) {
        UserHolder userInfo = sysUserService.getUserInfo();
        SysUser sysUser = userInfo.getSysUser();

        ColumnDescriptionUser columnDescriptionUser = new ColumnDescriptionUser();
        columnDescriptionUser.setUserId(sysUser.getUserId());
        columnDescriptionUser.setTableCode(tableCode);
        List<ColumnDescription> columnDescriptionList = columnDescriptionUserService.queryColumnByTableCode(columnDescriptionUser);

        if (columnDescriptionList.isEmpty()) {//为空，先添加部门模板数据
            ColumnDescription columnDescription = new ColumnDescription();
            BeanUtils.copyProperties(columnDescriptionUser, columnDescription);
            columnDescription.setDeptId(sysUser.getDeptId().toString());

            List<ColumnDescription> descriptionList = baseMapper.selectList(new QueryWrapper<>(columnDescription).orderBy(true, true, "sequence"));

            for (ColumnDescription description : descriptionList) {
                ColumnDescriptionUser descriptionUser = new ColumnDescriptionUser();
                BeanUtils.copyProperties(description, descriptionUser);
                descriptionUser.setUserId(sysUser.getUserId());
                columnDescriptionUserService.save(descriptionUser);
            }
        }

        for (CustomColumnVo customColumnVo : list) {
            ColumnDescriptionUser descriptionUser = new ColumnDescriptionUser();
            BeanUtils.copyProperties(customColumnVo, descriptionUser);
            descriptionUser.setField(customColumnVo.getDataIndex());
            descriptionUser.setUserId(sysUser.getUserId());
            descriptionUser.setVisible(customColumnVo.getExhibition());
            columnDescriptionUserService.updateById(descriptionUser);
        }

    }

    private List<ColumnDescription> getColumnDescriptions(String tableCode) {
        UserHolder userInfo = sysUserService.getUserInfo();
        SysUser sysUser = userInfo.getSysUser();

        ColumnDescriptionUser columnDescriptionUser = new ColumnDescriptionUser();
        columnDescriptionUser.setUserId(sysUser.getUserId());
        columnDescriptionUser.setTableCode(tableCode);
        List<ColumnDescription> list = columnDescriptionUserService.queryColumnByTableCode(columnDescriptionUser);

        if (list.isEmpty()) {//如果用户数据为空，取用户对应部门的模板数据
            ColumnDescription columnDescription = new ColumnDescription();
            BeanUtils.copyProperties(columnDescriptionUser, columnDescription);
            columnDescription.setDeptId(sysUser.getDeptId().toString());
            return baseMapper.selectList(new QueryWrapper<>(columnDescription).orderBy(true, true, "sequence"));
        }
        return list;
    }

}